
//正式服，maoxiaoqi.com  sxs.com.cn
// 测试服，apptestv80jnhovz9.maoxiaoqi.com


function checkSite() {
  let site = window.location.href;
  if(site.indexOf("/v2/")>-1){
    if(site.indexOf("apptest")>-1){
      return 2;
    }else{
      return 1;
    }
  }else{
    return 3;
  }
}
function checkSite2() {
    let site = window.location.href;
    if(site.indexOf("sxs.com.cn")>-1){
        return '.sxs.com.cn';
    }else if(site.indexOf("maoxiaoqi.com")>-1){
        return '.maoxiaoqi.com';
    }else{
        return '.maoxiaoqi.com';
    }
  }
// function requestBigData(){return (checkSite()==3?'/bigdata/':'https://tradebigdata.maoxiaoqi.com/');}
function requestBigData(){return "https://tradebigdata"+(checkSite()!=1?'test':'')+".maoxiaoqi.com/";}
function requestOSS(){return (checkSite()==3?'/OSS':'https://emailcloud.oss-cn-hangzhou.aliyuncs.com/ ');}
function ajax_url(){return (checkSite()==3?'/api':'')+"/ajax_data.php";}
function uploadUrl(){return (checkSite()==3?'/api':'')+"/uploadyx.php";}
function edmtaskUrl(){return (checkSite()==3?'/api':'')+"/edmtask.php";}
function requestUrl(){return (checkSite()==3?'/api':'')+"/request.php";}
function requestHelp(){return (checkSite()==3?'/api':'')+"/client/help/request.php";}
function requestRedis(){return (checkSite()==3?'/api':'')+"/client/config/language.php";}
function requestMxrr(){return (checkSite()==3?'/api':'')+"/client/checkmxrr.php";}
function uploadWD(){return (checkSite()==3?'/api':'')+"/module/mupload.php";}
function checkCname(){return (checkSite()==3?'/api':'')+"/v2/getCname.php";}

function isTestB2B() {return checkSite()!=1?true:false;}
function requestMgsSocket() {return "wss://notifytest.maoxiaoqi.com/ws";}
// function requestMgsSocket() {return "wss://notify"+(checkSite()!=1?'test':'')+".maoxiaoqi.com/ws";}

function requestUploadALY(){return ("https://b2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Storage/Upload/UploadFile";}
function requestYJYUploadALY(){return ("https://b2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Storage/Upload/GetOSSToken_aliyun";}
function requestB2BSso(){return ("https://b2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/sso/sso/";}
function requestB2BRegister(){return ("https://b2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Admin/Register/";}
function requestB2BMerchant(){return ("https://b2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Merchant/Goods/";}
function requestB2BGoods(){return ("https://b2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Merchant/Goods/";}
function requestB2BDomain() {return ("https://b2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Merchant/SiteDomain/";}
function requestB2BWebsite(){return ("https://b2b"+(checkSite()!=1?'test':'')+checkSite2())+"/api/site_manager/";}
function requestIM() {return "wss://im"+checkSite2();}
function requestB2BSiteGoods(){return ("https://b2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Merchant/SiteGoods/";}
function requestB2BShopGuide(){return ("https://b2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/ShopGuide/LiveVideo/";}
function requestB2BCustomer() {return ("https://b2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Customer/Enquire/";}
function requestB2BOrder() {return ("https://b2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Customer/Order/";}
function requestB2BSaveInfo() {return ("https://b2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Merchant/Shop/SaveInfo/";}



// S2B start
function requestS2BMarket() {return (checkSite()==3?'/s2b':"https://s2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Trader/Market/";}
function requestS2BOrder() {return (checkSite()==3?'/s2b':"https://s2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Trader/Order/";}
function requestS2BProduct() {return (checkSite()==3?'/s2b':"https://s2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/System/Product/";}
function requestS2BRegister() {return (checkSite()==3?'/s2b':"https://s2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Trader/Register/";}
function requestS2BGetAreaDict() {return (checkSite()==3?'/s2b':"https://s2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Common/Area/GetAreaDict/";}
function requestS2BGetDict() {return (checkSite()==3?'/s2b':"https://s2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Common/Dict/GetDict/";}
function requestS2BUploadALY(){return (checkSite()==3?'/s2b':"https://s2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Storage/Upload/UploadFile";}
function requestS2BSellRegister(){return (checkSite()==3?'/s2b':"https://s2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Supplier/Register/";}
function requestS2BSellProduct(){return (checkSite()==3?'/s2b':"https://s2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/Supplier/Product/";}
function requestS2BSso(){return (checkSite()==3?'/s2b':"https://s2b"+(checkSite()!=1?'test':'')+checkSite2())+"/App/sso/sso/";}

function requestAiBigData(){return ('https://aibigdata'+(checkSite()!=1?'test':'')+'.maoxiaoqi.com')}
function requestClueData(){return (checkSite()==3?'/saleserver':"https://saleserver"+(checkSite()!=1?'test':'')+".maoxiaoqi.com")}
// function requestClueData(){return 'https://saleserver'+(checkSite()!=1?'test':'')+'.maoxiaoqi.com'}
// function requestS2BGetTrade(){return "https://s2b"+(checkSite()!=1?'test':'')+checkSite2()+"App/Trader/Register/GetTrade";}

// function requestLBS() {return (checkSite()==3?'/lbs':"https://engineapi"+checkSite2()+"/request.php");}
function requestLBS(){return (checkSite()==3?'/lbs':'http://engineapi'+checkSite2())+"/request.php";}
function requestFB(){return (checkSite()==3?'/fb':'https://facebook'+(checkSite()!=1?'test':'')+checkSite2());}

function requestWhatsapp(){return (checkSite()==3?'/whatsapp':'https://whatsapp'+(checkSite()!=1?'test':'')+checkSite2());}
http://facebooktest.maoxiaoqi.com/

function requestClass(){return (checkSite()==3?'/liveclass':'https://liveclass'+(checkSite()!=1?'':'')+".maoxiaoqi.com")}

// 下载TXT
function downloadTXT(filename, text) {
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', filename);
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
}
// 提取纯文本
function ToText(HTML){
    var input = HTML;
    if (input) {
    return input.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi,'').replace(/<[^>]+?>/g,'').replace(/\s+/g,' ').replace(/ /g,' ').replace(/>/g,' ').replace(/&nbsp;/ig,' ');
    } else {
    return input;
    }
}
  /**
   * 函数防抖
   */
  function debounce(fn, wait = 1000) {
    let timer;
    return function () {
      let context = this;
      let args = arguments;
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(context, args);
      }, wait)
    }
  }
  /**
   * 函数节流
   */
  function throttle(fn, wait = 1000) {
    let timer;
    return function () {
      if (timer != null) return;
      let context = this;
      let args = arguments;
      fn.apply(context, args);
      timer = setTimeout(() => {
        timer = null;
      }, wait);
    }
  }

// 检测是否有中文
function ifYouNeed(str,type){
    if(type=='Chinese'){
        if (escape(str).indexOf( "%u" )<0){
            return false
        } else {
            return true
        }
    }
}

// 计算相差天数
function datedifference(sDate1, sDate2) {    //sDate1和sDate2是2006-12-18格式 
    var dateSpan,
        iDays;
    sDate1 = Date.parse(sDate1);
    sDate2 = Date.parse(sDate2);
    dateSpan = sDate2 - sDate1;
    dateSpan = Math.abs(dateSpan);
    console.log(dateSpan)
    iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
    return iDays
};


// 时间转时间戳
function timeStamp(date){
    date = date.substring(0,19);    
    date = date.replace(/-/g,'/'); 
    var timestamp = new Date(date).getTime();
    return timestamp
}
//计算字符总长度
function  bytesLnegth(str){
    var count=str.length;
   for(var i=0;i<str.length;i++){
        if(str.charCodeAt(i)>255){
           count++;
        }    
    }
    return count;
}
//字符串转化为json函数代码:
function formatasjson (str) {
    try{
        var json = $.parseJSON(str);
    }catch (e) {
        $(".spin-container").hide();
        // alertModal("提示","网络不稳定，请您稍后重试！");
        return false;
    }
    if("message" in json){
        json.message = getTipLanguage(json.message);
    }
    return json;
}
//json转化为字符串函数代码:
function forstring (json) {
    return JSON.stringify(json);
}
//设置cookie
function setCookie(name,value) {
    var exp = new Date();
    exp.setTime(exp.getTime() + 30*24*60*60*1000);
    document.cookie = name + "="+ encodeURI (value) + ";expires=" + exp.toGMTString();
}
//获取cookie
function getCookie(c_name) {
    if (document.cookie.length>0)
    {
        var c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1)
        {
            c_start=c_start + c_name.length+1;
            var c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return decodeURI(document.cookie.substring(c_start,c_end));
            //编码，解码 encodeURI()   decodeURI()
        }
    }
    return "";
}
//删除cookie
function delCookie(name){
    var exp = new Date();
    exp.setTime(exp.getTime() - 3600);
    var cval=getCookie(name);
    if(cval!=null) {
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + "";
        document.cookie="SAAS4=0;expires=" + exp.toGMTString()+";path=/module";
        document.cookie="SAAS4=0;expires=" + exp.toGMTString()+";path=/testor";
        document.cookie="SAAS4=0;expires=" + exp.toGMTString()+";path=/client";
        document.cookie="SAAS4=0;expires=" + exp.toGMTString()+";path=/client2";
    }
}
//检查被登陆后重重新登录登录
function checkLogin(){
    var login_user = getCookie("cookie_user");
    if(login_user!=""){
        login_user = formatasjson(login_user);
        var data = {
            module: "system",
            action: "login",
            devid:login_user.devid,
            email: login_user.username,
            password: login_user.password,
            kick: login_user.kick
        };
        $.ajax({
            type: "POST",  //提交方式必须为post
            url: requestUrl(),
            data: JSON.stringify(data),
            success: function (result){
                var jsonResult = formatasjson(result);
                //触发c端程序
                if (jsonResult.state){
                    var cookie = getCookie("SAAS4");
                    var json_s ={
                        cookie:cookie
                    };
                    json_s = JSON.stringify(json_s);
                    TJSCall.ExecCMD("AutoLogin",json_s);
                }else{
                    var json_e ={
                        error:jsonResult.message
                    };
                    json_e = JSON.stringify(json_e);
                    TJSCall.ExecCMD('AutoLogin', json_e);
                }
            }
        });
    }
}
//重新登录并刷新页面
function commonLogin(){
    var login_user = getCookie("cookie_user");
    if(login_user!="" && login_user!=undefined){
        login_user = formatasjson(login_user);
        var data = {
            module: "system",
            action: "login",
            devid:login_user.devid,
            email: login_user.username,
            password: login_user.password,
            kick: login_user.kick
        };
        $.ajax({
            type: "POST",  //提交方式必须为post
            url: requestUrl(),
            data: JSON.stringify(data),
            success: function (result){
                var json = formatasjson(result);
                if(json.state){
                    selfModal(json.message,3000);
                    //发送SAAS4 给UI 框架
                    var cookie = getCookie("SAAS4");
                    var json_s ={
                        cookie:cookie
                    };
                    json_s = JSON.stringify(json_s);
                    TJSCall.ExecCMD("AutoLogin",json_s);
                    window.location.reload()
                }else{
                    alertModal("提示",json.message);
                    return false;
                }
            }
        })
    }
    else{
        console.log(1111);
        alertModal(LANGS.tips,LANGS.loginExpiration);
    }
}
//自动登录功能
function selfLogin(){
    var login_user = getCookie("cookie_user");
    if(login_user!=""){
        login_user = $.parseJSON(login_user);
        if (login_user.sfl == "1"){
            var data = {
                module: "system",
                action: "login",
                devid:login_user.devid,
                email: login_user.username,
                password: login_user.password,
                kick: login_user.kick
            };
            $.ajax({
                type: "POST",  //提交方式必须为post
                url: requestUrl(),
                data: JSON.stringify(data),
                success: function (result){
                    var jsonResult = formatasjson(result);
                    //触发c端程序
                    if (jsonResult.state){
                        var ygbh = jsonResult.data.dwyg.ygbh;
                        var dwbh = jsonResult.data.dwyg.dwbh;
                        var ygxm = jsonResult.data.dwyg.ygxm;
                        var dwmc = jsonResult.data.dwyg.dwmc;
                        var option = getCookie("rmb-system");
                        if (option == null) {
                            option = "";
                        }
                        var cookie = getCookie("SAAS4");
                        var json = {
                            op: option,
                            cookie: cookie,
                            dwyg: {
                                ygbh: ygbh,
                                dwbh: dwbh,
                                ygxm:ygxm,
                                dwmc:dwmc
                            }
                        };
                        var json_str = JSON.stringify(json);
                        TJSCall.ExecCMD('AppLogin', json_str);
                    }else{
                        alertModal(LANGS.tips, jsonResult.message);
                        return false;
                    }
                }
            });
        }
    }
}
//文件base64编码并且保存sessionStorage->"file_base64"
function base64(id){
    var file = $("#"+id);
    var file_data= file[0].files[0];
    var reader = new FileReader();
    reader.readAsDataURL(file_data);
    reader.onload = function(e){
        var file_str = e.target.result;
        sessionStorage.setItem("file_base64",file_str);
    };
}

// 
//获取时间函数
function getNowTime(){
    var now = new Date();
    var time = now.getFullYear() + "-" +((now.getMonth()+1)<10?"0":"")+(now.getMonth()+1)+"-"+(now.getDate()<10?"0":"")+now.getDate()+"" +
        " "+(now.getHours()<10 ? "0"+now.getHours():now.getHours())+":"+(now.getMinutes()<10 ? "0"+now.getMinutes():now.getMinutes())+":"
        +(now.getSeconds()<10 ? "0"+now.getSeconds():now.getSeconds());
    return time;
}
function getTime(type,num){
    var date = new Date();
    var time ="";
    switch (type){
        case "month":
            var ms = num * (1000 * 60 * 60 * 24 * 30);
            var now = new Date(date.getTime() + ms);
            time = now.getFullYear() + "-" +((now.getMonth()+1)<10 ? "0":"")+(now.getMonth()+1);
            return time;
            break;
        case "day":
            var ms = num * (1000 * 60 * 60 * 24);
            var now = new Date(date.getTime() + ms);
            time = now.getFullYear() + "-" +((now.getMonth()+1)<10 ? "0":"")+(now.getMonth()+1)+"-"+((now.getDate()<10) ? "0":"")+(now.getDate());
            return time;
            break;
        case "minute":
            var ms = num * (1000 * 60);
            var now = new Date(date.getTime() + ms);
            var time = now.getFullYear() + "-" +((now.getMonth()+1)<10?"0":"")+(now.getMonth()+1)+"-"+(now.getDate()<10?"0":"")+now.getDate()+"" +
                " "+(now.getHours()<10 ? "0"+now.getHours():now.getHours())+":"+(now.getMinutes()<10 ? "0"+now.getMinutes():now.getMinutes());
            return time;
            break;
        default:
            return "";
            break;
    }
}
function format(sjc,type) {
    var time = new Date(sjc);
    var y = time.getFullYear();
    var m = time.getMonth()+1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    if(type=="day"){
      return y+'-'+add0(m)+'-'+add0(d);
    }else{
      return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
    }
}
function add0(m){return m<10?'0'+m:m }
//获取随机数 x - y
function getRandom(x,y) {
    var rand = parseInt(Math.random() * (x - y + 1) + y);
    return rand;
}
//框架要求支持方法
function AppMsg(s,t) {
    var oData = {};
    oData.op = 'Msg';
    oData.text = s;
    oData.title = t;
    TJSCall.ExecCMD('AppWin',JSON.stringify(oData));
}
//国家字典模块
function handleCR(arr){
    var country = {
        "ar":"阿根廷",
        "cl":"智利",
        "co":"哥伦比亚",
        "cr":"哥斯达黎加",
        "ec":"厄瓜多尔",
        "gb":"英国",
        "in":"印度",
        "kr":"韩国",
        "pa":"巴拿马",
        "pe":"秘鲁",
        "py":"巴拉圭",
        "ru":"俄罗斯",
        "ua":"乌克兰",
        "us":"美国",
        "uy":"乌拉圭",
        "ve":"委内瑞拉",
        "pk":"巴基斯坦",
        "za":"南非",
    };
    var data = [];
    $.each(arr,function(k,v){
        data.push({ cr:v,name:country[v]});
    });
    return data;
}
//生成随机数【1，9】
function randomNum(minNum,maxNum){
    switch(arguments.length){
        case 1:
            return parseInt(Math.random()*minNum+1);
            break;
        case 2:
            return parseInt(Math.random()*(maxNum-minNum+1)+minNum);
            break;
        default:
            return 0;
            break;
    }
}
//打开外部链接
function openUrl(sUrl){
    //WEB浏览器打开crm
    if(getCookie("userinfo") && getCookie("userinfo")!="false"){
        console.log(sUrl)
       window.open(sUrl);
    }else{
        TJSCall.ExecCMD('OpenUrl','{"url":"'+sUrl+'"}');
    }
}
//获取iframe参数 id为iframe（id）
function GetIframeQueryString(name,id){
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r =window.parent.document.getElementById(id).contentWindow.location.search.substr(1).match(reg);
    if (r != null) {
        return decodeURI(r[2]);
    }
    return null;
}

// import {websiteName} from "../../config/webConfig"
function getTipLanguage(key){
    var language = LANGS.accountState;
    var str = key;
    if(key in language){
        str = language[key];
    }
    return str;
}
//截取字符串长度 英文1 汉字2
function subString(str, len, hasDot) {
    var newLength = 0;
    var newStr = "";
    var chineseRegex = /[^\x00-\xff]/g;
    var singleChar = "";
    var strLength = str.replace(chineseRegex, "**").length;
    for (var i = 0; i < strLength; i++) {
        singleChar = str.charAt(i).toString();
        if (singleChar.match(chineseRegex) != null) {
            newLength += 2;
        }
        else {
            newLength++;
        }
        if (newLength > len) {
            break;
        }
        newStr += singleChar;
    }
    if (hasDot && strLength > len) {
        newStr += "...";
    }
    return newStr;
}
/**
 *  redis 存储
 *  action 操作方法 get set del clear
 *  store_key  => custom_search 保存的对应 key
 *  search  搜索值
 */
function redisWork(action,search,store_key) {
    search = decodeURI(search);
    var data = {
        module:"search_key",
        action:action,
        search:search,
        store_key:store_key
    };
    $.post(requestRedis(),data,function (res) {
        showRedisData(res);
    })
}
//冒泡事件
function stopPropagation(e) {
    if (e.stopPropagation){
        e.stopPropagation();
    } else{
        e.cancelBubble = true;
    }
}
/**
 * data是json对象，Name是根据什么字段去重
 */
function jsonDelDouble(data, Name) {
    var map = {}, dest = [];
    for (var i = 0; i < data.length; i++) {
        var ai = data[i];
        if (i == 0) {
            dest.push(ai);
        } else {
            var filterData = dest.filter(function (e) {
                return e[Name] == ai[Name];
            })
            if (filterData.length == 0) {
                dest.push(ai);
            }
        }
    }
    return dest;
}
/**
 *  wangeditor  图片编辑
 */
window._width = "60";
window._imgBase = "";
window._time = "";
$(document).on("click",".w-e-text-container .w-e-text img",function (){
    $(this).attr("id","this_img");
    var val = "";
    window._imgBase = "";
    window._width = parseInt($(this).css("width"));
    if($("#this_img").parent().prop("nodeName")=="A"){
        val = $(this).parent().attr("href");
    }
    var form = '<div id="_imgbox" style="width: 100%;height: 100%;position: absolute;left:0;top:0;z-index: 10000;">' +
        '<div id="_imgbox_pop" style="width: 100%;height: 100%;background-color: #ffffff;opacity: 0;position: absolute;left:0;top:0;z-index: -1;"></div>' +
        '<div style="position: absolute;top: 50%;left: 50%;margin: -90px -150px;width: 300px;height:180px;' +
        'border-radius: 4px;border: 1px solid #d4d4d4;box-shadow: 0 0 10px #d4d4d4;padding: 10px;background-color: #ffffff;">' +
        '<div style="height: 50px;line-height: 50px;">' +
        '<button class="btn btn-info" onclick="_imgChoose()">'+LANGS.replace+'</button>&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-default" onclick="del_imgbox()">'+LANGS.del+'</button>' +
        '<i class="icon-common icon-close-gray m fr" onclick="close_imgbox()"></i>'+
        '<input class="hide" type="file" id="img_file"/></div>' +
        '<div style="margin-top: 10px;">' +
        '<input style="width:100%;" class="onlyBottomLine" type="text" id="img_href" value="'+val+'" placeholder="'+LANGS.link+'http://"/></div>' +
        '<div style="margin-top: 30px;position: relative;">' +
        '<div style="width:100%;height: 4px;background-color: #d4d4d4;position: absolute;left: 0;top:0;">' +
        '<div id="img_width_slider" style="width: 12px;height: 12px;border-radius: 100%;background-color: #FF7800;position: absolute;top: -4px;' +
        'left:'+(window._width/1920)*268+'px;"></div>' +
        '</div>' +
        '<input class="opacity-0" style="width:100%;height: 10px;" type="range" step="1" min="1" max="1920" id="img_size" value="'+window._width+'"/>' +
        '<div id="img_width" style="padding-left:'+(window._width/1920)*240+'px;">'+window._width+'px</div>' +
        '</div></div></div>';
    if($("#_imgbox").length==0){
        $("body").after(form);
    }
    window._time = setInterval(function () {
        var src = $("#this_img").attr("src");
        if(window._imgBase!=""){
            src = window._imgBase;
        }
        $("#this_img").attr("src",src).css("width",window._width);
    },1);
});
$(document).on("click","#_imgbox_pop",function () {
    close_imgbox();
});
//图片选择 大小
$(document).on("input","#img_size",function () {
    window._width = $(this).val();
    $("#img_width").css("padding-left",(window._width/1920)*240+"px").text(window._width+'px');
    $("#img_width_slider").css("left",(window._width/1920)*268+"px");
});
$(document).on("change","#img_file",function () {
    var file = $(this)[0].files[0];
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(e) {
        window._imgBase = e.target.result;
    }
});
function _imgChoose(){
    $("#img_file").click();
}
function del_imgbox(){
    close_imgbox("del");
}
function close_imgbox(action) {
    clearInterval(window._time);
    if(action!="del"){
        var html = $("#this_img").prop("outerHTML");
        html = html.replace('id="this_img"',"");
        var href = $("#img_href").val();
        if($("#this_img").parent().prop("nodeName")!="A"){
            if(href!=""){
                $("#this_img").after('<a target="_blank" href="'+href+'">'+html+'</a>');
            }else{
                $("#this_img").after(html);
            }
        }else{
            if(href!=""){
                $("#this_img").parent().after('<a target="_blank" href="'+href+'">'+html+'</a>');
                $("#this_img").parent().remove();
            }else{
                $("#this_img").parent().html(html);
                $("#this_img").remove();
            }
        }
    }
    $("#this_img").remove();
    $("#_imgbox").remove();
}
/**
 * 图标   鼠标进出事件
 * @icon-common hover
 **/
$(document).on("mouseenter",".icon-common.hover",function () {
    $(this).addClass("h-active");
});
$(document).on("mouseleave",".icon-common.hover",function () {
    $(this).removeClass("h-active");
});

// import {domainNameList} from '../../config/webConfig';
// const hostName = location.host;
// let isHiddenMXQInfo = false;
// let websiteName = '贸小七';
// for(let item in domainNameList){
//   if(new RegExp(item).test(hostName)){
//     websiteName = domainNameList[item];
//     isHiddenMXQInfo = true;
//     break;
//   }
// }
//模态框-结合boostrap
function alertModal(title,content,type="0"){
    $("#myModalLabel").text(title);
    $(".modal-body").html(content);
    //注销前一次的确定事件
    $(".modal-confirm").off("click");
    $("#myModal").modal("show");
    if(type=="0"){
        if(content=="请重新登录!" || content=="ERR_PLEASELOGIN" || content == LANGS.loginAgain){
            //WEB浏览器
            var cookie_user = getCookie("cookie_user");
            console.log(getCookie("cookie_user"))
            if(cookie_user){
                $(".modal-confirm").click(function (){
                    setTimeout(function (){
                        keepLogin();
                    },500)
                })
            }else{
                $(".modal-confirm").click(function (){
                    window.location.href =  localStorage.getItem('isHiddenMXQInfo') === 'true' ? '/' : '/login.php';
                    return false;
                })
            }
        }
        else{
            $(".modal-cancel").hide();
        }
    }else{
        $(".modal-cancel").show();
    }
}
//自销框调用
function selfModal(content,time){
    $("#selfChange .content-text").html(content);
    $("#selfChange").fadeIn();
    setTimeout(function(){
        $("#selfChange").fadeOut();
    },time);
}
//提示进度条调用
function selfProgressBar(content,precent,type){
    $("#progressBar .content-text").html(content);
    $("#progressBar .progress-bar").css("width",precent);
    $("#progressBar").fadeIn();
}
function selfProgressBarFalse(content,precent){
    $("#progressBar .content-text").html(content);
    $("#progressBar .progress-bar").css("width",precent).removeClass("progress-bar-success").addClass("progress-bar-danger");
    setTimeout(function(){
        $("#progressBar").fadeOut();
    },2000);
    setTimeout(function(){
        $("#progressBar .progress-bar").removeClass("progress-bar-danger").addClass("progress-bar-success");
    },2500)
}
$(document).on("click",".form-body .form-input .form-tip",function () {
    $(this).parent().find(".input").focus();
});
function getStrParam(str, name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = str.match(reg);
    if (r != null) return r[2];
    return '';
}
//width、height调用时传入具体像素值，控制大小 ,不传则默认图像大小
function getBase64Image(img, width, height) {
    var canvas = document.createElement("canvas");
    canvas.width = width ? width : img.width;
    canvas.height = height ? height : img.height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    var dataURL = canvas.toDataURL();
    return dataURL;
}
function getCanvasBase64(img) {
    const that = this;
    var image = new Image();
    //至关重要
    image.crossOrigin = '';
    image.src = img;
    //至关重要
    var deferred = $.Deferred();
    if (img) {
        image.onload = function () {
            console.log(that.getBase64Image);
            deferred.resolve(that.getBase64Image(image));//将base64传给done上传处理
            // document.getElementById("container2").appendChild(image);
        }
        return deferred.promise();//问题要让onload完成后再return sessionStorage['imgTest']
    }
}
// 滚动到顶部
function scrollTop(element, scrollTop) {
    $(element).animate({
        scrollTop
    }, 500);
    // setTimeout(() => {
    //     $(element).scrollTop(scrollTop);  
    // }, 500);
};
